package com.jiepos.mpos.core.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.core.util.GlobalUtils;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 
 * <p>
 * 标题: —— session过滤器
 * @author 娄伟峰
 * @version 1.0

 */
 
public class DisableUrlSessionFilter implements Filter {
	public final Logger log = LoggerFactory.getLogger(getClass());
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
			if (!(request instanceof HttpServletRequest)) {
				chain.doFilter(request, response);
				return;
			}
		
		    HttpServletRequest request1 = (HttpServletRequest) request;
	        HttpServletResponse response1 = (HttpServletResponse) response;
	        HttpSession session = request1.getSession();     
	        
	        // 获得用户请求的URI
	        String path = request1.getRequestURI();
	        String contextPath = request1.getContextPath();
	        String url = path.substring(contextPath.length());
	        
	    	String postUri = request1.getRequestURI();
			log.debug("preHandle filter: "+postUri+" ip : "+this.getIpAddr(request1));
		    String loginUser = String.valueOf(session.getAttribute(SystemConstant.SESSION_LOGIN_USER));
		    log.debug("session loginuser:"+loginUser);
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;
	
			if (httpRequest.isRequestedSessionIdFromURL()) {					 
				if (session != null)
					session.invalidate();
			}
			// wrap response to remove URL encoding
			HttpServletResponseWrapper wrappedResponse = new HttpServletResponseWrapper(
					httpResponse) {
				@Override
				public String encodeRedirectUrl(String url) {
					return url;
				}
	
				public String encodeRedirectURL(String url) {
					return url;
				}
	
				public String encodeUrl(String url) {
					return url;
				}
	
				public String encodeURL(String url) {
					return url;
				}
			};
		 	if((postUri.contains(".jsp") || postUri.contains(".do")) ){
				log.debug("preHandle if ="+postUri);
				if (postUri.contains("/loginSystem.do") || postUri.contains("/logoutSystem.do") ||
						postUri.contains("/areaFiles.do")   || postUri.contains("findMenuTreeList.do")||
						postUri.contains("/timeout.jsp") || postUri.contains("/login.jsp")|| postUri.contains("/images.jsp")||
						postUri.contains("noauth.jsp")||postUri.contains("main_right.jsp")||postUri.contains("head.jsp")||
						postUri.contains("billResult.do")||postUri.contains("cmbcBillResult.do")) {	
				
					chain.doFilter(request, wrappedResponse);
					return;
				}else{
					if(StringUtils.isBlank(loginUser)){
						response1.sendRedirect(request1.getContextPath()+"/module/common/timeout.jsp");
						return;
					}
				//	log.info("用户账号为 : "+loginUser +"  用户IP为 :"+this.getIpAddr(request) + " postUri: "+postUri +" queryString:"+request.getQueryString());
					boolean temp = true;
					try {
						temp = check(request1, wrappedResponse);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(!temp){
						response1.sendRedirect(request1.getContextPath()+"/module/common/noauth.jsp");
						return ;
					}
					//response1.sendRedirect(request1.getContextPath()+"/module/common/timeout.jsp");
					chain.doFilter(request, wrappedResponse);
					return;
				}
			}else{
				chain.doFilter(request, wrappedResponse);
				log.debug("preHandle filter1: "+postUri);
				return;
			}  
			 
		//	log.debug("preHandle filter1: "+postUri);
		//	return;
			
		
	}
	public boolean check(HttpServletRequest request, HttpServletResponse response)  throws Exception{
		
		String postUri = request.getRequestURI();
		Enumeration rnames=request.getParameterNames();
		String loginUser = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_USER));
		List tempList = (List) request.getSession().getAttribute(SystemConstant.SESSION_AUTH_LIST);
 
		String str = "";
		for (Enumeration e = rnames ; e.hasMoreElements() ;) {
		         String thisName=e.nextElement().toString();
		        String thisValue=request.getParameter(thisName);
		        str = str+";"+ thisName+"="+thisValue;
		}
		log.info("用户账号为 : "+loginUser +"  用户IP为 :"+this.getIpAddr(request) + " postUri: "+postUri +" queryString:"+request.getQueryString()+" formdata:"+str);
		if(!postUri.contains("http")){
		/*	WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
			RedisTemplate redisTemplate = (RedisTemplate)wac.getBean("redisTemplate");
			HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();*/
			List allList = SystemConstant.MENU_URL_LIST;//(List)hash.entries(SystemConstant.CACHE_ALLAUTHURLLIST);
		//	List allList = (List)redisTemplate.opsForList().index(SystemConstant.CACHE_ALLAUTHURLLIST,1);
			if(allList == null ){
				return false;
			}
			if(allList.contains(postUri.replace("/"+GlobalUtils.getAppName(), ""))){
				if(!tempList.contains(postUri.replace("/"+GlobalUtils.getAppName(), "")) ){
					return false;
				}else{
					return true;
				}
			}else{
				return true;
			}
			
		 
		}
		return true;
	}
	public void init(FilterConfig config) throws ServletException {
		
	}

	   /**
     * 通过HttpServletRequest返回IP地址
     * @param request HttpServletRequest
     * @return ip String
     * @throws Exception
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }



	public void destroy() {
	}
}
